﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using ProTrack.Api.Helper;
using ProTrack.Dto;
using ProTrack.Entity;
using ProTrack.IServices.Stock;
using ProTrack.Report;
using ProTrack.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ProTrack.Api.Controllers
{
    /// <summary>
    /// 其他入库
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class OtherWareHouseController : Controller
    {
        public OtherWareHouseController(IOtherWareHouseServices services, LogHelper LogHeLper)
        {
            Services = services;
            this.LogHelper = LogHelper;
        }
        public IOtherWareHouseServices Services { get; }
        public LogHelper LogHelper { get; }

        /// <summary>
        /// 获取所有其他入库
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetAll")]
        public async Task<IActionResult> GetAll()
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var list = await Services.GetAllAsync();
                status.Data = list;
                status.Count = list.Count();
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";

                //写日志
                await LogHelper.WriteErrorLog("其他入库-获取所有", ex, HttpContext);
            }

            return Ok(status);
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="Ids">模型数组</param>
        /// <returns></returns>
        [HttpDelete("DelAll")]
        public async Task<IActionResult> DelAll([FromForm] string Ids)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var arr = Ids.SplitId();
                var isSuccess = await Services.Delete(arr);
                if (isSuccess)
                {
                    status.Msg = "删除成功";
                }
                else
                {

                    status.Code = -1;
                    status.Msg = "删除失败，请稍后重试";
                }
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";

                //写日志
                await LogHelper.WriteErrorLog("其他入库-批量删除", ex, HttpContext);
            }

            return Ok(status);
        }

        /// <summary>
        /// 删除单体
        /// </summary>
        /// <param name="Id">模型数组</param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<IActionResult> Del([FromForm] int Id)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var isSuccess = await Services.Delete(Id);
                if (isSuccess)
                {
                    status.Msg = "删除成功";
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "删除失败，请稍后重试。";
                }
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("其他入库-删除", ex, HttpContext);
            }
            return Ok(status);
        }

        /// <summary>
        /// 分页获取
        /// </summary>
        /// <param name="PageIndex"></param>
        /// <param name="PageSize"></param>
        /// <param name="Number">编号</param>
        /// <param name="RealName">经办人</param>
        /// <param name="WareHouseId">仓库编号</param>
        /// <param name="Status">状态</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Get([FromQuery] int PageIndex, [FromQuery] int PageSize, [FromQuery] string Number, [FromQuery] string RealName, [FromQuery] string WareHouseId, [FromQuery] string Status)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                Number = Number ?? "";
                RealName = RealName ?? "";
                WareHouseId = WareHouseId ?? "";
                Status = Status ?? "";

                var list = await Services.GetAsync(PageIndex, PageSize, Number, RealName, WareHouseId, Status);
                status.Data = list;
                status.Count = await Services.GetCountAsync(Number, RealName, WareHouseId, Status);
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("其他入库-分页获取", ex, HttpContext);
            }

            return Ok(status);
        }

        /// <summary>
        /// 新增其他入库单
        /// </summary>
        /// <param name="model">新增其他入库</param>
        /// <param name="OtherWareHouseItemString">其他入库明细表</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Add([FromForm] OtherWareHouse model, [FromForm] string OtherWareHouseItemString)
        {
            var status = BaseStatus.CreateInstance();
            List<OtherWareHouseItem> list = new List<OtherWareHouseItem>();

            try
            {
                if (!string.IsNullOrEmpty(OtherWareHouseItemString))
                {
                    list = JsonConvert.DeserializeObject<List<OtherWareHouseItem>>(OtherWareHouseItemString);

                    list.ForEach(x =>
                    {
                        x.OtherWareHouseId = model.Id;
                    });
                }
                model.CreateTime = StringHelper.GetTimeNow();
                model.Creator = User.Identity.Name;

                var result = await Services.AddAsync(model, list);
                if (result)
                {
                    status.Msg = "新增成功";
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "新增失败,请检查数据。";
                }

            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("其他入库-新增", ex, HttpContext);
            }
            return Ok(status);

        }

        /// <summary>
        /// 修改其他入库单
        /// </summary>
        /// <param name="model">模型</param>
        /// <param name="OtherWareHouseItemString">字符串子项</param>
        /// <returns></returns>
        [HttpPut]
        public async Task<IActionResult> Update([FromForm] OtherWareHouse model, [FromForm] string OtherWareHouseItemString)
        {
            var status = BaseStatus.CreateInstance();
            List<OtherWareHouseItem> list = new List<OtherWareHouseItem>();
            try
            {
                if (!string.IsNullOrEmpty(OtherWareHouseItemString))
                {
                    list = JsonConvert.DeserializeObject<List<OtherWareHouseItem>>(OtherWareHouseItemString);
                    list.ForEach(x =>
                    {
                        x.OtherWareHouseId = model.Id;

                    });
                }
                model.UpdateTime = StringHelper.GetTimeNow();
                model.Updater = User.Identity.Name;
                var isSuccess = await Services.UpdateAsync(model, list);
                if (isSuccess)
                {
                    status.Msg = "修改成功";

                    //操作日志
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "修改失败，请检查数据。";
                }

            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "编辑失败，请检查已出库的物料产品数量是否充足！编辑单据自动还原原始单据的物料产品数量。";
                //写日志
                await LogHelper.WriteErrorLog("其他入库-修改", ex, HttpContext);
            }
            return Ok(status);
        }


        /// <summary>
        /// 获取商品
        /// </summary>
        /// <param name="OtherWareHouseId">关联的入库单据id</param>
        /// <param name="WareHouseId">入库仓Id</param>
        /// <returns></returns>
        [HttpGet("GetOtherWareHouseItemById")]
        public async Task<IActionResult> GetOtherWareHouseItemById([FromQuery] string OtherWareHouseId, [FromQuery] string WareHouseId)
        {
            var status = BaseStatus.CreateInstance();
            try
            {

                var list = await Services.GetOtherWareHouseItemById(OtherWareHouseId, WareHouseId);
                status.Data = list;
                status.Count = list.Count();
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("其他入库-获取商品", ex, HttpContext);
            }

            return Ok(status);
        }

        /// <summary>
        /// 修改状态
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="Status">状态</param>
        /// <returns></returns>
        [HttpPut("UpdateStatus")]
        public async Task<IActionResult> UpdateStatus([FromForm] long Id, [FromForm] int Status)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                // 根据 Id 查询数据库，找到对应的对象
                var isSuccess = await Services.UpdateStatus(Id, Status);


                if (isSuccess)
                {
                    var msg = Status == 0 ? "反审成功" : "审核成功";
                    status.Code = 0;
                    status.Msg = msg;
                }
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("其他入库-修改状态", ex, HttpContext);
            }

            return Ok(status);
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <returns></returns>
        [HttpGet("Export")]
        public async Task<IActionResult> Export()
        {
            try
            {

                var list = await Services.GetAllAsync();
                var TitleArray = new ReportDomain[] {
                    new ReportDomain{ Title="序号",Fileld="No"},
                    new ReportDomain{ Title="编号",Fileld="Number"},
                    new ReportDomain{ Title="入货仓Id",Fileld="WareHouseId"},
                    new ReportDomain{ Title="入库仓名称",Fileld="WareHouseName"},
                    new ReportDomain{ Title="经办人",Fileld="RealName"},
                    new ReportDomain{ Title="类型",Fileld="WareHouseMode"},
                    new ReportDomain{ Title="状态",Fileld="Status"},
                    new ReportDomain{ Title="入库时间",Fileld="WarehouseDate"},
                    new ReportDomain{ Title="备注",Fileld="Remark"},
                };
                var fileArray = BaseReport.Export(list, "其他入库信息", TitleArray);

                return File(new System.IO.MemoryStream(fileArray), "application/octet-stream", "其他入库信息.xls");
            }
            catch (Exception ex)
            {

                //此处应当日志记录
                await LogHelper.WriteErrorLog("其他入库-导出", ex, HttpContext);
                return new JsonResult(BaseStatus.CreateInstance(-1, "导出失败，服务器异常请稍后再试！"));
            }

        }
    }
}
